package com.example.JPetStore.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.JPetStore.Common;
import com.example.JPetStore.dao.ItemDao;
import com.example.JPetStore.dao.ProductDao;
import com.example.JPetStore.dao.UserDao;
import com.example.JPetStore.domain.Product;
import com.example.JPetStore.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;

@RequestMapping("/api")
@RestController
public class ApiController {
    @Autowired
    ItemDao itemDao;
    @Autowired
    ProductDao productDao;
    @Autowired
    UserDao userDao;

    @GetMapping("/CalculatePriceServlet")
    public String CalculatePriceServlet( @RequestParam("item_id")String item_id, @RequestParam("item_number")String item_number){

        JSONObject data=new JSONObject();

        BigDecimal bd1= itemDao.GainPrice(item_id);
        BigDecimal bd2=new BigDecimal(item_number);
        BigDecimal bd3=bd1.multiply(bd2);

        data.put("TotalPrice",bd3);

//        System.out.println(data);
        return Common.Success(data);
    }

    @GetMapping("/ProductWindowServlet")
    public String ProductWindowServlet( @RequestParam("cate_id")String cateId){
        ArrayList<Product> products= productDao.queryProducts(cateId);

        JSONObject data=new JSONObject();

        data.put("Products",products);
        return Common.Success(data);
    }

    @GetMapping("/ShowAllItemsServlet")
    public String ShowAllItemsServlet( @RequestParam("keyword")String keyword){

        JSONObject data=new JSONObject();
        ArrayList<String> str_items=itemDao.showItemsById(keyword);

        data.put("Items",str_items);
        return Common.Success(data);
    }

    @GetMapping("/UsernameIsExistServlet")
    public String UsernameIsExistServlet( @RequestParam("nick_name")String nickName){

        User user = userDao.queryUser1(nickName);

        JSONObject data=new JSONObject();
        if(user!=null){
            data.put("exist",true);
        }else{
            data.put("exist",false);
        }
        return Common.Success(data);
    }
}
